import * as vscode from "vscode";
import { CSSVariableParser } from "./utlit/CssVariableParser";
import { CssReplace } from "./utlit/CssReplace";
export function activate(context: vscode.ExtensionContext) {
  console.log("程序启动");
  let parser: CSSVariableParser;
  parser = new CSSVariableParser();
  const cssReplace = new CssReplace();
  parser.collectVariables();
  const watcher = vscode.workspace.createFileSystemWatcher("**/*.{css,scss}");
  watcher.onDidChange(() => parser.collectVariables());
  watcher.onDidCreate(() => parser.collectVariables());
  watcher.onDidDelete(() => parser.collectVariables());
  // 自动补全
  context.subscriptions.push(
    vscode.languages.registerCompletionItemProvider(
      ["css", "scss", "vue", "html"],
      {
        provideCompletionItems(document, position) {
          const linePrefix = document
            .lineAt(position)
            .text.slice(0, position.character);
          const match = linePrefix.match(
            /(#[\da-fA-F]*|[\d.]+(?:px|rem|em|%)?)$/
          );
          if (match) {
            console.log(parser.valueToVars);
            return parser.getSuggestions(match[0]);
          }
          return [];
        },
      },
      "#",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "0"
    )
  );
  let disposable = vscode.commands.registerCommand(
    "extension.handlePaste",
    async () => {
      const editor = vscode.window.activeTextEditor;
      if (!editor) {
        return;
      }
      const clipboardText = await vscode.env.clipboard.readText();
      let result;
      try {
        result = await cssReplace.replaceCssVariables(
          parser.valueToVars,
          clipboardText
        );
      } catch (err) {
        vscode.window.showErrorMessage("修改失败: " + String(err));
        return;
      }
      if (result) {
        editor.edit((editBuilder) => {
          const selections = editor.selections;
          selections.forEach((selection) => {
            if (selection.isEmpty) {
              editBuilder.insert(selection.start, result);
            } else {
              editBuilder.replace(selection, result);
            }
          });
        });
      }
    }
  );

  context.subscriptions.push(disposable);
}
